package com.lagou.config;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 *
 * 解析mapper xml
 * @author stevejson
 */
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }
    public void parse(InputStream inputStream) throws DocumentException {

        Document document = new SAXReader().read(inputStream);


        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        this.createMappedStatement(rootElement.selectNodes("//select"), SqlCommandType.SELECT, namespace);
        this.createMappedStatement(rootElement.selectNodes("//insert"), SqlCommandType.INSERT, namespace);
        this.createMappedStatement(rootElement.selectNodes("//update"), SqlCommandType.UPDATE, namespace);
        this.createMappedStatement(rootElement.selectNodes("//delete"), SqlCommandType.DELETE, namespace);
    }

    private void createMappedStatement(List<Element> elements, SqlCommandType sqlCommandType, String namespace){
        for (Element element : elements) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sqlText = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setResultType(resultType);
            mappedStatement.setSql(sqlText);
            mappedStatement.setSqlCommandType(sqlCommandType);
            configuration.getMappedStatementMap().put(namespace+"."+id, mappedStatement);
        }
    }

}
